import 'package:flutter/cupertino.dart';
import 'package:macos_ui/macos_ui.dart';
import '../models/mcp_tool.dart';

/// MCP 配置对话框
class ConfigDialog extends StatefulWidget {
  final McpConfig? initialConfig;

  const ConfigDialog({super.key, this.initialConfig});

  @override
  State<ConfigDialog> createState() => _ConfigDialogState();
}

class _ConfigDialogState extends State<ConfigDialog> {
  late McpConnectionType _connectionType;
  final _commandController = TextEditingController();
  final _argsController = TextEditingController();
  final _envController = TextEditingController();
  final _sseUrlController = TextEditingController();
  final _headersController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _connectionType = widget.initialConfig?.type ?? McpConnectionType.cmd;

    if (widget.initialConfig != null) {
      _commandController.text = widget.initialConfig!.command ?? '';
      _argsController.text = widget.initialConfig!.args?.join(' ') ?? '';
      _envController.text =
          widget.initialConfig!.env?.entries
              .map((e) => '${e.key}=${e.value}')
              .join('\n') ??
          '';
      _sseUrlController.text = widget.initialConfig!.sseUrl ?? '';
      _headersController.text =
          widget.initialConfig!.headers?.entries
              .map((e) => '${e.key}: ${e.value}')
              .join('\n') ??
          '';
    }
  }

  @override
  void dispose() {
    _commandController.dispose();
    _argsController.dispose();
    _envController.dispose();
    _sseUrlController.dispose();
    _headersController.dispose();
    super.dispose();
  }

  Map<String, String>? _parseKeyValuePairs(String text, String separator) {
    if (text.trim().isEmpty) return null;

    final map = <String, String>{};
    for (final line in text.split('\n')) {
      final parts = line.split(separator);
      if (parts.length == 2) {
        map[parts[0].trim()] = parts[1].trim();
      }
    }
    return map.isNotEmpty ? map : null;
  }

  void _onSave() {
    McpConfig? config;

    if (_connectionType == McpConnectionType.cmd) {
      if (_commandController.text.trim().isEmpty) {
        _showError('Command is required');
        return;
      }

      config = McpConfig.cmd(
        command: _commandController.text.trim(),
        args: _argsController.text.trim().isEmpty
            ? null
            : _argsController.text.trim().split(RegExp(r'\s+')),
        env: _parseKeyValuePairs(_envController.text, '='),
      );
    } else {
      if (_sseUrlController.text.trim().isEmpty) {
        _showError('SSE URL 不能为空');
        return;
      }

      config = McpConfig.sse(
        url: _sseUrlController.text.trim(),
        headers: _parseKeyValuePairs(_headersController.text, ':'),
      );
    }

    Navigator.of(context).pop(config);
  }

  void _showError(String message) {
    showMacosAlertDialog(
      context: context,
      builder: (context) => MacosAlertDialog(
        appIcon: const Icon(CupertinoIcons.exclamationmark_triangle),
        title: const Text('错误'),
        message: Text(message),
        primaryButton: PushButton(
          controlSize: ControlSize.large,
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('确定'),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MacosSheet(
      child: ConstrainedBox(
        constraints: const BoxConstraints(
          maxWidth: 600,
          minWidth: 500,
          maxHeight: 100,
        ),
        child: Padding(
          padding: const EdgeInsets.all(0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 标题栏区域
              Container(
                padding: const EdgeInsets.fromLTRB(24, 20, 20, 16),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: MacosTheme.of(context).dividerColor,
                      width: 0.5,
                    ),
                  ),
                ),
                child: Row(
                  children: [
                    const Icon(
                      CupertinoIcons.gear_alt,
                      size: 20,
                    ),
                    const SizedBox(width: 10),
                    const Text(
                      'MCP 连接配置',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const Spacer(),
                    MacosIconButton(
                      icon: const Icon(
                        CupertinoIcons.xmark_circle_fill,
                        size: 20,
                      ),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                  ],
                ),
              ),
              // 内容区域
              Flexible(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 连接类型选择区域
                      _buildSectionTitle('连接类型'),
                      const SizedBox(height: 12),
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: MacosTheme.of(context).canvasColor.withValues(alpha: 0.5),
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(
                            color: MacosTheme.of(context).dividerColor.withValues(alpha: 0.5),
                          ),
                        ),
                        child: Column(
                          children: [
                            _buildRadioOption(
                              McpConnectionType.cmd,
                              '命令行 (stdio)',
                              '通过标准输入输出与MCP服务通信',
                            ),
                            const SizedBox(height: 12),
                            _buildRadioOption(
                              McpConnectionType.sse,
                              'HTTP/SSE',
                              '通过HTTP和Server-Sent Events与MCP服务通信',
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 24),
                      // 配置详情区域
                      if (_connectionType == McpConnectionType.cmd) ...[
                        _buildCmdConfig(),
                      ] else ...[
                        _buildSseConfig(),
                      ],
                    ],
                  ),
                ),
              ),
              // 底部按钮区域
              Container(
                padding: const EdgeInsets.fromLTRB(24, 16, 24, 20),
                decoration: BoxDecoration(
                  border: Border(
                    top: BorderSide(
                      color: MacosTheme.of(context).dividerColor,
                      width: 0.5,
                    ),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    PushButton(
                      controlSize: ControlSize.large,
                      secondary: true,
                      onPressed: () => Navigator.of(context).pop(),
                      child: const Text('取消'),
                    ),
                    const SizedBox(width: 12),
                    PushButton(
                      controlSize: ControlSize.large,
                      onPressed: _onSave,
                      child: const Text('连接'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 13,
        fontWeight: FontWeight.w600,
      ),
    );
  }

  Widget _buildRadioOption(
    McpConnectionType value,
    String title,
    String description,
  ) {
    final isSelected = _connectionType == value;
    return GestureDetector(
      onTap: () {
        setState(() {
          _connectionType = value;
        });
      },
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: isSelected
              ? MacosTheme.of(context).primaryColor.withValues(alpha: 0.1)
              : null,
          borderRadius: BorderRadius.circular(6),
          border: Border.all(
            color: isSelected
                ? MacosTheme.of(context).primaryColor.withValues(alpha: 0.5)
                : MacosTheme.of(context).dividerColor.withValues(alpha: 0.3),
            width: 1.5,
          ),
        ),
        child: Row(
          children: [
            MacosRadioButton<McpConnectionType>(
              value: value,
              groupValue: _connectionType,
              onChanged: (value) {
                setState(() {
                  _connectionType = value!;
                });
              },
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 13,
                      fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    description,
                    style: TextStyle(
                      fontSize: 11,
                      color: MacosTheme.of(context).typography.caption1.color,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCmdConfig() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('命令行配置'),
        const SizedBox(height: 12),
        _buildFieldLabel('命令', required: true),
        const SizedBox(height: 6),
        MacosTextField(
          controller: _commandController,
          placeholder: '例如: npx 或 python 或 node',
        ),
        const SizedBox(height: 4),
        _buildFieldHint('可执行命令的路径或名称'),
        const SizedBox(height: 16),
        _buildFieldLabel('参数'),
        const SizedBox(height: 6),
        MacosTextField(
          controller: _argsController,
          placeholder: '例如: -m mcp_server 或 server.js',
        ),
        const SizedBox(height: 4),
        _buildFieldHint('命令行参数，用空格分隔'),
        const SizedBox(height: 16),
        _buildFieldLabel('环境变量'),
        const SizedBox(height: 6),
        MacosTextField(
          controller: _envController,
          placeholder: 'DEBUG=true\nPORT=3000',
          maxLines: 3,
        ),
        const SizedBox(height: 4),
        _buildFieldHint('格式: KEY=VALUE，每行一个'),
      ],
    );
  }

  Widget _buildFieldLabel(String label, {bool required = false}) {
    return Row(
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
        if (required) ...[
          const SizedBox(width: 4),
          const Text(
            '*',
            style: TextStyle(
              fontSize: 12,
              color: CupertinoColors.systemRed,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildFieldHint(String hint) {
    return Text(
      hint,
      style: TextStyle(
        fontSize: 11,
        color: MacosTheme.of(context).typography.caption1.color,
      ),
    );
  }

  Widget _buildSseConfig() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('HTTP/SSE 配置'),
        const SizedBox(height: 12),
        _buildFieldLabel('服务器 URL', required: true),
        const SizedBox(height: 6),
        MacosTextField(
          controller: _sseUrlController,
          placeholder: 'http://localhost:3000/mcp',
        ),
        const SizedBox(height: 4),
        _buildFieldHint('MCP服务器的HTTP端点地址'),
        const SizedBox(height: 16),
        _buildFieldLabel('HTTP 请求头'),
        const SizedBox(height: 6),
        MacosTextField(
          controller: _headersController,
          placeholder: 'Authorization: Bearer token\nX-API-Key: key',
          maxLines: 3,
        ),
        const SizedBox(height: 4),
        _buildFieldHint('格式: KEY: VALUE，每行一个'),
      ],
    );
  }
}
